package com.example.demo1122.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo1122.DTO.ConversationMapDTO;
import com.example.demo1122.domain.LoginStudent;
import com.example.demo1122.domain.ResponseResult;
import com.example.demo1122.entity.Conversation;
import com.example.demo1122.mapper.ConversationMapper;
import com.example.demo1122.service.IConversationService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class ConversationServiceImpl extends ServiceImpl<ConversationMapper, Conversation> implements IConversationService {
    @Resource
    private  ConversationMapper conversationMapper;

    @Override
    public ResponseResult createConversation(Conversation conversation){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginStudent loginStudent = (LoginStudent) authentication.getPrincipal();
        String studentID = loginStudent.getStudent().getStudentID();
        if(conversation.getClassID() == null){
            return new ResponseResult(0, "error", "未获取到课堂ID");
        }
        if (studentID == null){
            return new ResponseResult(0, "error", "未获取到学生ID");
        }
        try {
            LocalDateTime startTime = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            conversation.setStudentID(studentID);
            conversation.setStartTime(startTime.format(formatter));
            conversation.setConversationEvaluation(2);
            conversationMapper.insert(conversation);
            Map<String, Integer> conversationMap = new HashMap<>();
            conversationMap.put("conversationID", conversation.getConversationID());
            return new ResponseResult(1, "success", conversationMap);
        } catch (Exception e) {
            return new ResponseResult(0, "error", e);
        }
    }

    @Override
    public ResponseResult selectStudentConversation(String studentID){
        try {
            List<Conversation> conversationList =  conversationMapper.selectAllByStudentID(studentID);
            HashMap<String, List<Conversation>> conversationMap = new HashMap<>();
            conversationMap.put("data", conversationList);
            return new ResponseResult(1, "success", conversationMap);
        } catch (Exception e) {
            return new ResponseResult(0, "error", e);
        }
    }


    @Override
    public ResponseResult getConversationNum(String studentID){
        Integer conversationNum = conversationMapper.getConversationNum(studentID);
        Map<String, Integer> conversationNumMap = new HashMap<>();
        conversationNumMap.put("conversationNum", conversationNum);
        return new ResponseResult(1, "success", conversationNumMap);
    }

    @Override
    public ResponseResult evaluateConversation(Conversation conversation) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginStudent loginStudent = (LoginStudent) authentication.getPrincipal();
        String studentID = loginStudent.getStudent().getStudentID();
        conversation.setStudentID(studentID);
        if (conversation.getConversationEvaluation() != 0 && conversation.getConversationEvaluation() != 1){
            return new ResponseResult(0, "error", "对会话的评价输入有误");
        }
        try {
            conversationMapper.update(conversation);
            return new ResponseResult(1, "success");
        } catch (Exception e) {
            return new ResponseResult(0, "error", e);
        }
    }

    @Override
    @Transactional
    public ResponseResult endConversation(Conversation conversation) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginStudent loginStudent = (LoginStudent) authentication.getPrincipal();
        String studentID = loginStudent.getStudent().getStudentID();
        conversation.setStudentID(studentID);
        if (!conversationMapper.isConversationIDExists(conversation.getConversationID())){
            return new ResponseResult(0, "error","该会话不存在");
        }
        LocalDateTime endTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        conversation.setEndTime(endTime.format(formatter));
        conversationMapper.update(conversation);
        return new ResponseResult(1,"end conversation success");
    }

    @Override
    public ResponseResult showHistory(Conversation conversation) {
        try {
            List<Conversation> allConversation = conversationMapper.showHistory(conversation);
            HashMap<String,List<Conversation>> conversationMap = new HashMap<>();
            conversationMap.put("data", allConversation);
            return new ResponseResult(1,"success",conversationMap);
        } catch (Exception e) {
            return new ResponseResult(0, "error", e);
        }
    }

    @Override
    public ResponseResult showClassConversation(Integer classID) {
        try {
            List<Conversation> allConversation = conversationMapper.selectAllByClassID(classID);
            HashMap<String, List<Conversation>> conversationMap = new HashMap<>();
            conversationMap.put("data", allConversation);
            return new ResponseResult(1, "success", conversationMap);
        } catch (Exception e) {
            return new ResponseResult(0, "error", e);
        }
    }

    @Override
    public ResponseResult searchConversation(Conversation conversation) {
        try {
            List<Conversation> allConversation = conversationMapper.fuzzySelect(conversation);
            HashMap<String, List<Conversation>> conversationMap = new HashMap<>();
            conversationMap.put("data", allConversation);
            return new ResponseResult(1, "success", conversationMap);
        } catch (Exception e) {
            return new ResponseResult(0, "error", e);
        }
    }

    @Override
    public ResponseResult chapterConversationInfo(Integer classID, Integer chapterID, String studentID) {
        if (classID == null){
            return new ResponseResult(0,"error","未获取到classID");
        }
        if (chapterID == null){
            return new ResponseResult(0,"error","未获取到chapterID");
        }
        try {
            List<Conversation> conversationList = conversationMapper.selectAllByChapterID(classID, chapterID, studentID);
            return new ResponseResult(1,"success",conversationList);
        } catch (Exception e) {
            return new ResponseResult(0,"error",e);
        }
    }

    @Override
    public ResponseResult getCourseConversationNum_interval(Integer courseID, Integer chapterID, Integer Interval) {
        try {
            List<ConversationMapDTO> conversationList = conversationMapper.getCourseConversationNum_interval(courseID,chapterID,Interval);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            Map<LocalDate, Long> dailyConversationCounts = conversationList.stream()
                    .collect(Collectors.groupingBy(
                            conversation -> LocalDate.parse(conversation.getStartTime(), formatter),
                            Collectors.counting()
                    ));
            // TODO: add chapterConversationCounts, show every chapter conversation pair
            Map<String, Long> chapterConversationCounts = conversationList.stream()
                    .collect(Collectors.groupingBy(
                            ConversationMapDTO::getChapterName,
                            Collectors.counting()
                    ));
            List<Map<?, Long>> mapList = new ArrayList<>();
            mapList.add(dailyConversationCounts);
            mapList.add(chapterConversationCounts);
            return new ResponseResult<>(1,"success", mapList);
        } catch (Exception e) {
            return new ResponseResult<>(0,"error", e);
        }
    }

    @Override
    public ResponseResult getCourseConversationNum_range(Integer courseID, Integer chapterID, String startSelectTime, String endSelectTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime range1 = LocalDateTime.parse(startSelectTime, formatter);
        LocalDateTime range2 = LocalDateTime.parse(endSelectTime, formatter);
        try {
            List<ConversationMapDTO> conversationList = conversationMapper.getCourseConversationNum_range(courseID, chapterID,range1, range2);
            Map<LocalDate, Long> dailyConversationCounts = conversationList.stream()
                    .collect(Collectors.groupingBy(
                            conversation -> LocalDate.parse(conversation.getStartTime(), formatter),
                            Collectors.counting()
                    ));
            // TODO: add chapterConversationCounts, show every chapter conversation pair
            Map<String, Long> chapterConversationCounts = conversationList.stream()
                    .collect(Collectors.groupingBy(
                            ConversationMapDTO::getChapterName,
                            Collectors.counting()
                    ));
            List<Map<?, Long>> mapList = new ArrayList<>();
            mapList.add(dailyConversationCounts);
            mapList.add(chapterConversationCounts);
            return new ResponseResult<>(1,"success", mapList);
        } catch (Exception e) {
            return new ResponseResult<>(0,"error", e);
        }
    }

    @Override
    public ResponseResult getClassConversationNum_interval(Integer classID, Integer chapterID, Integer Interval) {
        try {
            List<ConversationMapDTO> conversationList = conversationMapper.getClassConversationNum_interval(classID,chapterID,Interval);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            Map<LocalDate, Long> dailyConversationCounts = conversationList.stream()
                    .collect(Collectors.groupingBy(
                            conversation -> LocalDate.parse(conversation.getStartTime(), formatter),
                            Collectors.counting()
                    ));
            // TODO: add chapterConversationCounts, show every chapter conversation pair
            Map<String, Long> chapterConversationCounts = conversationList.stream()
                    .collect(Collectors.groupingBy(
                            ConversationMapDTO::getChapterName,
                            Collectors.counting()
                    ));
            List<Map<?, Long>> mapList = new ArrayList<>();
            mapList.add(dailyConversationCounts);
            mapList.add(chapterConversationCounts);
            return new ResponseResult<>(1,"success", mapList);
        } catch (Exception e) {
            return new ResponseResult<>(0,"error", e);
        }
    }

    @Override
    public ResponseResult getClassConversationNum_range(Integer classID, Integer chapterID, String startSelectTime, String endSelectTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime range1 = LocalDateTime.parse(startSelectTime, formatter);
        LocalDateTime range2 = LocalDateTime.parse(endSelectTime, formatter);
        try {
            List<ConversationMapDTO> conversationList = conversationMapper.getClassConversationNum_range(classID, chapterID,range1, range2);
            Map<LocalDate, Long> dailyConversationCounts = conversationList.stream()
                    .collect(Collectors.groupingBy(
                            conversation -> LocalDate.parse(conversation.getStartTime(), formatter),
                            Collectors.counting()
                    ));
            // TODO: add chapterConversationCounts, show every chapter conversation pair
            Map<String, Long> chapterConversationCounts = conversationList.stream()
                    .collect(Collectors.groupingBy(
                            ConversationMapDTO::getChapterName,
                            Collectors.counting()
                    ));
            List<Map<?, Long>> mapList = new ArrayList<>();
            mapList.add(dailyConversationCounts);
            mapList.add(chapterConversationCounts);
            return new ResponseResult<>(1,"success", mapList);
        } catch (Exception e) {
            return new ResponseResult<>(0,"error", e);
        }
    }

}
